package com.alogic.lucene.indexer;

import com.alogic.lucene.core.Indexer;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * 基于文件系统的实现
 *
 * @since 1.6.14.10 [20210510 duanyy] <br>
 */
public class FileSystem extends Indexer.Abstract{
    /**
     * dircectory
     */
    protected Directory index = null;

    protected Path home = null;

    @Override
    public Directory getDirectory() {
        return index;
    }

    @Override
    public long getLastBuildTime(String counter) {
        Path file = Paths.get(home.toString(),String.format(".%s.tt",counter));
        if (!Files.exists(file)){
            return 0;
        }
        try {
            List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
            if (!lines.isEmpty()){
                return Long.parseLong(lines.get(0));
            }
        }catch (Exception ex){
            logger.error("Can not read file :" + file.toUri());
            return 0;
        }
        return 0;
    }

    @Override
    public void commitLastBuildTime(String counter, long tt) {
        Path file = Paths.get(home.toString(),String.format(".%s.tt",counter));
        try {
            Files.write(file, String.valueOf(tt).getBytes());
        }catch (Exception ex){
            logger.error("Can not write file :" + file.toUri());
        }
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        home = Paths.get(PropertiesConstants.getString(p,"home","${alogic.home}/alogic-lucene/${id}",true)).normalize();
        try {
            logger.info("Use filesystem as lucene directory:" + home.toUri());
            if (!Files.exists(home)){
                Files.createDirectories(home);
            }
            index = FSDirectory.open(home);
        }catch (Exception ex){
            logger.error("Cannot open file system:" + home.toUri());
            logger.error(ExceptionUtils.getStackTrace(ex));
        }
    }

}
